package logview;

import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.ObjectName;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import logview.mbeans.LogFileManager;
import logview.mbeans.PropertyLogFile;

public class InitServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static transient final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(InitServlet.class);

	public static final String DOMAIN = "logview_"+System.currentTimeMillis();
	private MBeanServer server;
	public static String agentId;
	
	@Override
	public void init(ServletConfig config) throws ServletException {
		String filename = config.getServletContext().getRealPath("WEB-INF/logfiles.properties");
		log.debug(InitServlet.class.getName()+" initialized");
		
		createMBeanServer();
		// Add core mbeans
		LogFileManager manager = new LogFileManager();
		try {
			server.registerMBean(manager, LogFileManager.getObjectName());
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		// Add MBeans for loggers in logfiles.properties
		PropertyLogFile logfiles = new PropertyLogFile();
		logfiles.setFilename(filename);
		logfiles.addAll();
		try {
			server.registerMBean(logfiles, logfiles.getObjectName());
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

	}

	private void createMBeanServer() {
		server = MBeanServerFactory.createMBeanServer(DOMAIN);
		try {
			agentId = (String) server.getAttribute(ObjectName.getInstance("JMImplementation:type=MBeanServerDelegate"), "MBeanServerId");
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}
	
	@Override
	public void destroy() {
		log.debug(InitServlet.class.getName()+" destroyed");
		super.destroy();
		MBeanServerFactory.releaseMBeanServer(this.server);
	}
}
